// 历史记录页JS
Page({
  data: {
    // 情绪选项
    moodOptions: ['放松', '兴奋', '疲惫', '平静', '开心', '难过', '愤怒', '期待'],
    // 历史记录数据
    history: [],
    // 筛选后的历史记录
    filteredHistory: [],
    // 激活的筛选条件
    activeType: '',
    activeMood: ''
  },

  onLoad: function() {
    // 加载历史记录
    this.loadHistory();
  },

  onShow: function() {
    // 每次页面显示时重新加载历史记录
    this.loadHistory();
  },

  // 加载历史记录
  async loadHistory() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      const app = getApp();
      
      // 从后端获取历史记录
      const historyData = await app.loadDrawHistory();
      
      // 格式化时间
      const formattedHistory = historyData.map(item => ({
        ...item,
        time: this.formatTime(item.timestamp)
      }));
      
      this.setData({
        history: formattedHistory,
        filteredHistory: formattedHistory
      });
      
      // 应用当前筛选条件
      this.applyFilters();
    } catch (error) {
      console.error('加载历史记录失败:', error);
      wx.showToast({
        title: '加载失败，使用缓存数据',
        icon: 'none'
      });
      
      // 如果API调用失败，尝试使用缓存数据
      const app = getApp();
      if (app.globalData.cachedData && app.globalData.cachedData.drawHistory) {
        const cachedHistory = app.globalData.cachedData.drawHistory.map(item => ({
          ...item,
          time: this.formatTime(item.timestamp)
        }));
        
        this.setData({
          history: cachedHistory,
          filteredHistory: cachedHistory
        });
        this.applyFilters();
      }
    } finally {
      wx.hideLoading();
    }
  },

  // 按类型筛选
  filterByType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ activeType: type });
    this.applyFilters();
  },

  // 按情绪筛选
  filterByMood: function(e) {
    const mood = e.currentTarget.dataset.mood;
    this.setData({ activeMood: mood });
    this.applyFilters();
  },

  // 应用筛选条件
  applyFilters: function() {
    const { history, activeType, activeMood } = this.data;
    
    let filtered = history;
    
    // 按类型筛选
    if (activeType) {
      filtered = filtered.filter(item => item.type === activeType);
    }
    
    // 按情绪筛选
    if (activeMood) {
      filtered = filtered.filter(item => {
        // 检查标签中是否包含当前筛选的情绪
        return item.content && item.content.tags && item.content.tags.includes(activeMood);
      });
    }
    
    this.setData({ filteredHistory: filtered });
  },

  // 查看详情
  viewDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    
    // 直接跳转到结果页并传递historyId
    wx.navigateTo({
      url: `/pages/result/result?historyId=${id}`
    });
  },

  // 去抽盲盒
  goToHome: function() {
    wx.navigateTo({
      url: '/pages/index/index'
    });
  },

  // 格式化时间
  formatTime: function(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
});